import 'dart:io';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_score_container.dart';
import 'package:xindong/widgets/image/browser/xindong_images_browser.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/constants/history_message_constant.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/message.dart';
import 'package:transparent_image/transparent_image.dart';

class XinDongLiaoTianMessageImage extends StatefulWidget {
  final V2TimMessage message;

  const XinDongLiaoTianMessageImage({Key? key, required this.message}) : super(key: key);

  @override
  State<XinDongLiaoTianMessageImage> createState() => _XinDongLiaoTianMessageImageState();
}

class _XinDongLiaoTianMessageImageState extends State<XinDongLiaoTianMessageImage> {
  bool imageIsRender = false;
  late double positionRadio;

  /*
  为了解决，重复渲染的跳闪问题
  当现有图片队列只有一个，且上一个图片队列不存在时才进行更新，因为此时是发送了新的图片
  */

  @override
  void initState() {
    super.initState();
    positionRadio = 9 / 15;
  }

  @override
  didUpdateWidget(oldWidget) {
    var oldImgListLength = oldWidget.message.imageElem?.imageList?.length ?? 0;
    var currImgListLength = widget.message.imageElem?.imageList?.length ?? 0;
    if (currImgListLength == 1 && oldImgListLength == 0) {
      setState(() {
        imageIsRender = true;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  getBigPicUrl() {
    // 实际拿的是原图
    V2TimImage? img =
        MessageUtils.getImageFromImgList(widget.message.imageElem!.imageList, HistoryMessageDartConstant.oriImgPrior);
    return img == null ? widget.message.imageElem!.path! : img.url!;
  }

  Widget errorDisplay(BuildContext context, TUITheme? theme) {
    final I18nUtils ttBuild = I18nUtils(context);
    return Container(
      decoration: BoxDecoration(
          border: Border.all(
        width: 1,
        color: Colors.black12,
      )),
      height: 100,
      child: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.warning_amber_outlined,
              color: theme?.cautionColor,
              size: 16,
            ),
            Text(
              ttBuild.imt_origin("图片加载失败"),
              style: TextStyle(color: theme?.cautionColor),
            ),
          ],
        ),
      ),
    );
  }

  Widget getImage(image, {imageElem}) {
    Widget res = ClipRRect(
      borderRadius: const BorderRadius.all(Radius.circular(5)),
      child: image,
    );

    return res;
  }

  getImgWidthAndHeight(BoxConstraints constraints, double height, double width) {
    // 消息列表展示缩略图的大小
    double hwrate = height / width;
    double curWidth = min(width, constraints.maxWidth * 0.4);
    double curHeight = curWidth * hwrate;
    return {height: curHeight, width: curWidth};
  }

  V2TimImage? getImageFromList(V2TimImageTypesEnum imgType) {
    V2TimImage? img = MessageUtils.getImageFromImgList(widget.message.imageElem!.imageList,
        HistoryMessageDartConstant.imgPriorMap[imgType] ?? HistoryMessageDartConstant.oriImgPrior);
    if (img == null) {
      setState(() {
        imageIsRender = true;
      });
    }
    return img;
  }

  Widget imageBuilder(BoxConstraints constraints, TUITheme? theme, {V2TimImage? originalImg, V2TimImage? smallImg}) {
    if (originalImg == null) {
      // 有path
      if (widget.message.imageElem!.path!.isNotEmpty) {
        return getImage(Image.file(File(widget.message.imageElem!.path!), fit: BoxFit.fitWidth), imageElem: null);
      } else {
        return errorDisplay(context, theme);
      }
    } else if (widget.message.imageElem!.path!.isNotEmpty &&
        File(widget.message.imageElem!.path!).existsSync() &&
        !imageIsRender) {
      V2TimImage image = widget.message.imageElem!.imageList!.first!;
      // if local resources image is available, use it as priority
      return getImage(
          GestureDetector(
            onTap: () {
              XinDongImagesBrowser.show(list: [image.url], currentIndex: 0);
            },
            child: Image.file(File(widget.message.imageElem!.path!), fit: BoxFit.fitWidth),
          ),
          imageElem: e);
    } else if ((smallImg?.url ?? originalImg.url) != null && !imageIsRender) {
      double positionRadio = 1.0;
      if (smallImg?.width != null && smallImg?.height != null && smallImg?.width != 0 && smallImg?.height != 0) {
        positionRadio = (smallImg!.width! / smallImg.height!);
      }
      return Stack(
        alignment: AlignmentDirectional.topStart,
        children: [
          AspectRatio(
            aspectRatio: positionRadio,
            child: Container(
              decoration: const BoxDecoration(color: Colors.white),
            ),
          ),
          getImage(
              GestureDetector(
                onTap: () {
                  XinDongImagesBrowser.show(
                    list: [widget.message.imageElem!.imageList!.first!.url],
                    currentIndex: 0,
                  );
                },
                child:
                    // XinDongImageHelper.networkImageUrl(smallImg?.url ?? originalImg.url!,errorWidget:   errorDisplay(context, theme),fit: BoxFit.fitWidth,placeholder: Image(image: MemoryImage(kTransparentImage)),),

                    CachedNetworkImage(
                  imageUrl: smallImg?.url ?? originalImg.url!,
                  // use small image in message list as priority
                  errorWidget: (context, error, stackTrace) => errorDisplay(context, theme),
                  fit: BoxFit.fitWidth,
                  cacheKey: smallImg?.uuid ?? originalImg.uuid!,
                  placeholder: (context, url) => Image(image: MemoryImage(kTransparentImage)),
                  fadeInDuration: const Duration(milliseconds: 0),
                ),
              ),
              imageElem: e)
        ],
      );
    } else {
      // 有path
      if (widget.message.imageElem!.path!.isNotEmpty) {
        return getImage(
            GestureDetector(
              onTap: () {
                XinDongImagesBrowser.show(
                  list: [widget.message.imageElem!.imageList!.first!.url],
                  currentIndex: 0,
                );
              },
              child: Image.file(File(widget.message.imageElem!.path!), fit: BoxFit.fitWidth),
            ),
            imageElem: null);
      } else {
        return errorDisplay(context, theme);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    V2TimImage? originalImg = getImageFromList(V2TimImageTypesEnum.original);
    V2TimImage? smallImg = getImageFromList(V2TimImageTypesEnum.small);

    double positionRadio = 1.0;
    try {
      int? width = originalImg?.width;
      int? height = originalImg?.height;
      positionRadio = width! / height!;
    } catch (e) {
      mCatchPrint(e);
    }
    final isFromSelf = widget.message.isSelf == true;
    return XinDongLiaoTianMessageScoreContainer(
      hidden: isFromSelf,
      message: widget.message,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(5)),
          border: Border.all(color: const Color.fromRGBO(245, 166, 35, 0), width: 2),
        ),
        child: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            final theme = Provider.of<TUIThemeViewModel>(context).theme;
            return ConstrainedBox(
              constraints: BoxConstraints(maxWidth: positionRadio > 1 ? 160 : 100, minWidth: 0),
              child: imageBuilder(constraints, theme, originalImg: originalImg, smallImg: smallImg),
            );
          },
        ),
      ),
    );
  }
}
